package steed.util.random;

import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;

/**
 * 根据权重抽奖
 * @author battlesteed
 *
 */
public class WeightDraw {
	/**
     * 获取概率事件，几率最多支持3位小数
     *
     * @param map
     *            参数举例: Map(1=>20.1, 2=>29.9, 3=>50), 则20.1%几率返回1, 29.9%返回2,
     *            50%返回3
     * @return 返回键值
     */
    public <T> T getDraw(Map<T, Double> map,int multiple) {
         // 放大位数
 
        // 求和
        int sum = 0;
        Iterator<Entry<T, Double>> iter = map.entrySet().iterator();
        while (iter.hasNext()) {
            Entry<T, Double> entry = iter.next();
            Double v = entry.getValue();
            sum += v * multiple;
        }
 
        if (sum <= 0) {
            return null;
        }
        Random random = new Random();
        // 产生0-sum的整数随机
        int luckNum = random.nextInt(sum) + 1;
        int tmp = 0;
        iter = map.entrySet().iterator();
        while (iter.hasNext()) {
            Entry<T, Double> entry = iter.next();
            Double v = entry.getValue();
            tmp += v * multiple;
            if (luckNum <= tmp) {
                return entry.getKey();
            }
        }
        return null;
    }    
}
